#!/usr/bin/env python
# -*- coding: utf-8 -*-


##################################################################
#
#	Este script foi baseado(copiado) de um script escrito por:
#	Sidnei César Breianti
#	"http://www.pythonbrasil.com.br/moin.cgi/MaskEntry"
#
##################################################################
#
#		PyAcAdmin - Sistema Gerenciador de Academia
#
# 	Este arquivo faz parte do projeto PyAcAdmin
#	http://code.google.com/p/pyacadmin/
#	Desenvolvido por: Carlos Henrique Marques da Cunha Filho
#	rickadt@gmail.com
#
##################################################################
# example maskentry.py

import pygtk
pygtk.require('2.0')
import gtk
import re
from gtk import *
import gtk.gdk
import gobject




class EntryMask(gtk.Entry):

    def __init__(self):

        self.gtkentry=gtk.Entry.__init__(self)
        self.chars = re.compile(r'[\-\.\(\)/{_}|]')
        self.set_text('')
        hid = self.connect_after('insert-text', self.filter)
        self.set_data('handlerid', hid)


    def set(self, text, *args):

        hid = self.get_data('handlerid')
        self.handler_block(hid)
        self.set_text(text)
        self.set_position(-1)
        self.handler_unblock(hid)


    def filter(self, *args):
        _text=self.get_text()
        _text=self.unmask(_text)
        _new=self.mask(_text)
        gobject.timeout_add(1, self.set , _new)


    def validate(self, text_char, mask_char):

        num = re.compile(r'[0-9]')
        lettup = re.compile(r'[A-Z]')
        lettdw = re.compile(r'[a-z]')

        if mask_char == '9':
            valid = num.match(text_char)
        elif mask_char == 'a':
            valid = lettdw.match(text_char)
        elif mask_char == 'A':
            valid = lettup.match(text_char)
        elif mask_char == 'X':
            valid =  (num.match(text_char) or
                     lettdw.match(text_char) or
                     lettup.match(text_char))

        return valid

    def mask(self, _text):

        len_mask=int(len(self._mask))
        self._mask=list(self._mask)
        _len=int(len(_text))
        _text=list(_text)
        z=0
        new=''
        for n in range(len_mask):
            mask_char=self._mask[n]
            if z<_len:
                if self.chars.match(mask_char):
                    new=new+mask_char

                else:
                    text_char=_text[z]
                    if self.validate(text_char, mask_char):
                        new=new+text_char
                        z=z+1
        return new

    def unmask(self, _text):
        _text=self.chars.sub('',_text)
        return _text

    def set_mask(self, _mask):
        self._mask=_mask
        self.set_max_length(len(self._mask))

